<!DOCTYPE html>
<html>
<head>
    <title>Hello WebSocket</title>
    <script src="/webjars/sockjs-client/sockjs.min.js"></script>
    <script src="/webjars/stomp-websocket/stomp.min.js"></script>
    <script type="text/javascript">
        var stompClient = null;

        function setConnected(connected) {
            document.getElementById('connect').disabled = connected;
            document.getElementById('disconnect').disabled = !connected;
            document.getElementById('conversationDiv').style.visibility = connected ? 'visible' : 'hidden';
            document.getElementById('response').innerHTML = '';
        }

        function connect() {
            let socket = new SockJS('/gs-guide-websocket');
            stompClient = Stomp.over(socket);
            stompClient.connect({}, function(frame) {
                setConnected(true);
                console.log('Connected: ' + frame);
                //订阅消息 @SendTo("/topic/greetings")
                stompClient.subscribe('/topic/handle', function(greeting){
                    showGreeting(greeting.body+"");
                });
            });
        }

        function disconnect() {
            if (stompClient !== null) {
                stompClient.disconnect();
            }
            setConnected(false);
            console.log("Disconnected");
        }

        function sendName() {
            let name = document.getElementById('name').value;
            //发送消息 @MessageMapping("/hello")，/app是前缀
            stompClient.send("/app/handle", {}, name);
        }

        function showGreeting(message) {
            let response = document.getElementById('response');
            response.innerText += message + '\n';
        }
    </script>
</head>
<body>
<div>
    <button id="connect" onclick="connect();">Connect</button>
    <button id="disconnect" disabled="true" onclick="disconnect();">Disconnect</button>
</div>
<div id="conversationDiv">
    <label>Enter your name: </label><input type="text" id="name" />
    <button id="send" onclick="sendName();">Send</button>
    <p id="response"></p>
</div>
</body>
</html>